package de.uniba.wiai.lspi.chord.service.impl;

import de.uniba.wiai.lspi.chord.com.CommunicationException;
import de.uniba.wiai.lspi.chord.com.Node;

public class CheckPrimaryNodeTask implements Runnable {
	/**
	 * Reference on routing table.
	 */
	private References references;
	
	private Node localNode = null;
	
	private Object mutex = new Object();
	private boolean isTrying = false;
	
	CheckPrimaryNodeTask(References references, Node localNode) {
		if (references == null || localNode == null) {
			throw new NullPointerException(
					"Parameter references or Local Node may not be null!");
		}

		this.references = references;
		this.localNode = localNode;
	}
	
	@Override
	public void run() {
		try {
			if (localNode.isFusionNode()) {
				int crashedPrimaryIndex = -1; 
				for (int nodeIndex = 0; nodeIndex < NodeImpl.MAX_PRIMARY_NODES; ++nodeIndex) {
					Node primaryNode = this.references.getPrimary(nodeIndex);
					try {
						if (primaryNode != null) {
							primaryNode.ping();
						}
					} catch (CommunicationException e) {
						// Detected a primary node crashed
						crashedPrimaryIndex = this.references.getPrimaryIndex(primaryNode.getNodeID());
						System.err.println(this.localNode.getNodeURL() + " detected a primary node crashed: " + crashedPrimaryIndex + " " + primaryNode.getNodeURL());
						((NodeImpl) this.localNode).removePrimary(primaryNode.getNodeID());
						//TODO
						this.localNode.recoverPrimaryData(crashedPrimaryIndex);
						break;
					}
				}
			}
		} catch (CommunicationException e) {
			e.printStackTrace();
		}
	}
}
